package com.qf.utils;
import advanced.RowMapper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/*
杨威
2021/9/7
12:42
*/
public class DaoUtils {
    public static int commonsUpdate(String sql,Object...params){
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        try {
            connection=DbUtil.getConnection();
            preparedStatement=connection.prepareStatement(sql);
            for(int i=0;i<params.length;i++){
                preparedStatement.setObject(i+1,params[i]);
            }
            int i = preparedStatement.executeUpdate();
            return i;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtil.closeAll(connection,preparedStatement,null);
        }
        return 0;
    }
    public static <T> List<T> commonsSelect(String sql, RowMapper<T> rowMapper, Object...params){
        Connection connection = null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        List<T> list=new ArrayList<>();
        try {
            connection=DbUtil.getConnection();
            preparedStatement=connection.prepareStatement(sql);
            //如果params不为空，证明有参数，需要给占位符赋值
            if(params!=null){
                for(int i=0;i<params.length;i++){
                    preparedStatement.setObject(i+1,params[i]);
                }
            }
            resultSet=preparedStatement.executeQuery();
            while(resultSet.next()){
                T row = rowMapper.getRow(resultSet);
                list.add(row);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtil.closeAll(connection,preparedStatement,resultSet);
        }
        return list;
    }
}
